package com.itheima.aspect;

import cn.hutool.json.JSONUtil;
import com.itheima.vo.R;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @version 1.0
 * @description  全局响应体接收器 @ControllerAdvice
 * 用于处理所有的请求返回  ResponseBodyAdvice
 *  目的:根据响应类型不同可以做出相对应的处理;
 *  比如:对响应请求进行封装,比如返回的数据为String类型,可以对其进行封装成固定的响应格式
 * @package com.itheima.aspect
 */

@ControllerAdvice
public class MyResponseBodyAdvice implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if(selectedContentType.includes(MediaType.APPLICATION_OCTET_STREAM)){
            return body;
        }
        if(body instanceof R){
            return body;
        }
        if(body instanceof String){
            response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
            return JSONUtil.toJsonStr(R.okMsg((String) body));
        }
        return R.ok();
    }
}
